package com.tg.message.msg;

import static com.tg.appcommon.android.TGToast.showToast;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.appbase.custom.constant.EventConstants;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.tange.base.toolkit.StringUtils;
import com.tange.core.backend.service.http.ClientObserver;
import com.tange.module.statistics.TangeBizEventReport;
import com.tange.module.statistics.TangeBizStatisticsConstants;
import com.tg.appcommon.android.ClickableSpanHelper;
import com.tg.appcommon.android.PermissionUtil;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.business.IAppModule;
import com.tg.appcommon.business.ICarModule;
import com.tg.appcommon.car.IMapView;
import com.tg.appcommon.router.TGBusiness;
import com.tg.data.helper.DeviceItemHelper;
import com.tg.data.helper.DeviceTypeHelper;
import com.tg.data.helper.DeviceTypeStorage;
import com.tg.data.http.entity.EmptyBean;
import com.tg.data.http.entity.MessageDataBean;
import com.tg.data.http.entity.ShouldAiFeedbackBean;
import com.tg.message.R;
import com.tg.network.socket.http.TGHttp;

import java.util.HashMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 消息详情页底部信息
 */
public class MessageInfoView extends FrameLayout {

    private static final String TAG = MessagePlayActivity.TAG_PLAY + "MessageInfoView";

    private int statusBarHeight;

    private IMapView mIMapView;

    private View cloudServiceAdView;

    private View addressView;
    private TextView addressTv;

    private FrameLayout mapContainer;
    private View topContainer;
    private ImageView backBtn;
    private TextView messageDetailTv;

    private TextView messageTypeTv;
    private ImageView messageAiIv;

    private TextView dateTv;
    private TextView timeTv;

    private View deviceTypeLayout;
    private ImageView deviceTypeIv;
    private TextView deviceNameTv;

    private View downloadView;
    private TextView downloadTypeTv;
    private ImageView downloadStatusIcon;
    private ImageView downloadArrow;
    private View fullVideoView;

    private View aiFeedbackView;
    private View aiFeedbackViewYes;
    private View aiFeedbackViewNo;


    private boolean isVideoDownloadMode = false;

    private boolean isDownloadSuccess = false;

    private TextView alertSettingTv;

    private MessageDataHolder messageDataHolder;

    private boolean canLive = false;

    private Bundle savedInstanceState;

    private MessagePlayerView messagePlayerView;

    private Button mButtonView;
    private EditText editText;
    private static final int UUID_LENGTH = 12;
    private Activity activity;



    public void setActivity(Activity activity){
        this.activity = activity;
    }

    public void setMessagePlayerView(MessagePlayerView messagePlayerView) {
        this.messagePlayerView = messagePlayerView;
    }

    public MessageInfoView(Context context) {
        super(context);
        initView(context);
    }

    public MessageInfoView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);

    }

    public MessageInfoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    public void setSavedInstanceState(Bundle savedInstanceState) {
        this.savedInstanceState = savedInstanceState;
    }

    public void updateDownloadStatus(boolean isSuccess) {
        TGLog.i(TAG, "updateDownloadStatus: " + isSuccess);
        if (downloadStatusIcon != null) {
            downloadStatusIcon.post(() -> {
                if (isSuccess) {
                    isDownloadSuccess = true;
                    downloadStatusIcon.setImageResource(R.drawable.tange_ic_global_success);
                    downloadStatusIcon.setVisibility(VISIBLE);
                    downloadTypeTv.setText(R.string.video_is_saved_to_album);
                    downloadTypeTv.setTextColor(getResources().getColor(R.color.global_customize_main_color));
                    downloadArrow.setVisibility(View.GONE);
                } else {
                    downloadStatusIcon.setImageResource(R.drawable.tange_ic_global_failed);
                    downloadStatusIcon.setVisibility(VISIBLE);
                    downloadTypeTv.setText(R.string.video_is_download_failed);
                    downloadTypeTv.setTextColor(getResources().getColor(R.color.global_customize_fixed_color_error));
                    downloadArrow.setVisibility(View.GONE);
                }
            });
        }
    }

    public void refresh(MessageDataHolder messageDataHolder) {

        this.messageDataHolder = messageDataHolder;

        if (messageDataHolder.shouldShowCloudServiceAd()) {
            TangeBizEventReport.reportEvent(getContext(), TangeBizStatisticsConstants.Message_Detail_Cloud_Service_Ad_View_Count);
            cloudServiceAdView.setVisibility(View.VISIBLE);
            cloudServiceAdView.setOnClickListener(v -> {
                TangeBizEventReport.reportEvent(getContext(), TangeBizStatisticsConstants.Message_Detail_Cloud_Service_Ad_Click_Count);
                IAppModule iAppModule = TGBusiness.getAppModule();
                if (iAppModule != null) {
                    iAppModule.launchCloudServicePay(v.getContext(), messageDataHolder.getDeviceItem());
                }
            });
        }

        final int displayType = messageDataHolder.getDisplayType();

        final MessageDataBean.ItemsBean message = messageDataHolder.getEventMessage();

        if (message == null) return;

        if (displayType == MessageDataHolder.MSG_EVENT_TYPE_MAP) {
            topContainer.setVisibility(VISIBLE);
            findViewById(R.id.top_bar_alpha_bg).setVisibility(VISIBLE);
            messageDetailTv.setVisibility(VISIBLE);
            fullVideoView.setVisibility(GONE);
            downloadView.setVisibility(GONE);
            aiFeedbackView.setVisibility(GONE);
            messageDetailTv.setVisibility(GONE);

            backBtn.setImageResource(R.drawable.ic_back_btn_white);
            ICarModule iCarModule = TGBusiness.getCarModule();
            mIMapView = iCarModule.getMapView(getContext(), ICarModule.MAP_FROM_MESSAGE);
            if (mIMapView != null){
                mapContainer.setVisibility(VISIBLE);
                mIMapView.init(savedInstanceState);
                mapContainer.addView(mIMapView);

                String[] latlngData = message.getPos().split(",");
                if (latlngData.length == 3) {
                    double lat = Double.parseDouble(latlngData[1]);
                    double lng = Double.parseDouble(latlngData[0]);
                    float dir = Float.parseFloat(latlngData[2]);
                    if (mIMapView != null){
                        mIMapView.showMarker(lat, lng, dir);
                    }
                }
            }else {
                mapContainer.setVisibility(View.GONE);
            }

            if (!TextUtils.isEmpty(message.getAddr())) {
                addressView.setVisibility(VISIBLE);
                addressTv.setText(message.getAddr());
            } else {
                addressView.setVisibility(GONE);
            }

        } else if (displayType == MessageDataHolder.MSG_EVENT_TYPE_TEXT) {
            topContainer.setVisibility(VISIBLE);
            messageDetailTv.setVisibility(VISIBLE);
            messageDetailTv.setTypeface(null, Typeface.BOLD);
            messageTypeTv.setTypeface(null, Typeface.BOLD);
            fullVideoView.setVisibility(GONE);
            downloadView.setVisibility(GONE);
            aiFeedbackView.setVisibility(GONE);

            if (!TextUtils.isEmpty(message.getTag_msg())) {
                messageDetailTv.setText(message.getTag_msg());
            } else {
                messageDetailTv.setVisibility(GONE);
            }

            if (!TextUtils.isEmpty(message.getBtn_name()) && !TextUtils.isEmpty(message.getUrl())) {
                findViewById(R.id.service_btn_layout).setVisibility(VISIBLE);
                TextView serviceBtn = findViewById(R.id.btn_service);
                serviceBtn.setText(message.getBtn_name());
                serviceBtn.setOnClickListener(v -> onClickFull());
            }

            if (TextUtils.equals(messageDataHolder.getEventMessage().getMessage_type(), EventConstants.NOTICE)) {
                alertSettingTv.setVisibility(GONE);
            }
        } else {
            topContainer.setVisibility(GONE);
            messageDetailTv.setVisibility(GONE);
            fullVideoView.setVisibility(VISIBLE);
            downloadView.setVisibility(VISIBLE);
            aiFeedbackView.setVisibility(GONE);


            downloadTypeTv.setText(R.string.label_download_pic);
        }

        if (!messageDataHolder.shouldShowFullVideoEntry()) {
            fullVideoView.setVisibility(GONE);
        }

        if (messageDataHolder.getDeviceItem() != null){
            IAppModule iAppModule = TGBusiness.getAppModule();
            if (iAppModule.isLamp(messageDataHolder.getDeviceItem())){
                fullVideoView.setVisibility(VISIBLE);
            }else{
                if (iAppModule.isNoMedia(messageDataHolder.getDeviceItem())&&!DeviceItemHelper.hasServe(messageDataHolder.getDeviceItem())){
                    fullVideoView.setVisibility(GONE);
                }
            }
        }

        MessageDisplay messageDisplay = MessageDisplayMapping.get(messageDataHolder.getEventMessage().getTag());

        messageAiIv.setVisibility(message.isIs_ai_tag() ? VISIBLE : GONE);

        String deviceType = DeviceTypeStorage.readDeviceType(getContext(), message.getUuid());
        if (DeviceTypeHelper.isCar(deviceType)) {
            deviceTypeIv.setImageResource(R.drawable.ic_tange_global_icon_message_device_type_car);
        } else if (DeviceTypeHelper.isLockBell(deviceType)) {
            deviceTypeIv.setImageResource(R.drawable.ic_tange_global_icon_message_device_type_lock);
        } else {
            deviceTypeIv.setImageResource(R.drawable.ic_tange_global_icon_message_device_type_ipc);
        }

        if (!TextUtils.isEmpty(message.getTag_name())) {
            messageTypeTv.setText(message.getTag_name());
        } else {
            if (messageDisplay != null) {
                if (!TextUtils.isEmpty(message.getTag_msg())) {
                    messageTypeTv.setText(message.getTag_msg());
                } else {
                    messageTypeTv.setText(messageDisplay.msgLabelResId);
                }
                messageAiIv.setVisibility(messageDisplay.isAi ? VISIBLE : GONE);
            }
        }

        if (!TextUtils.isEmpty(messageDataHolder.getEventMessage().getStart_time())) {
            String[] dateArr = messageDataHolder.getEventMessage().getStart_time().split(" ");
            if (dateArr != null && dateArr.length == 2) {
                String date = dateArr[0].replace("-", ".");
                dateTv.setText(date);
                timeTv.setText(dateArr[1]);
            }

        }

        deviceNameTv.setText(messageDataHolder.getEventMessage().getNickname());

        if (messageDataHolder.noDeviceInfo()) {
            deviceTypeLayout.setVisibility(View.GONE);
        }

        long nowTs = System.currentTimeMillis() / 1000;
        long startTs = messageDataHolder.getEventMessage().getStart_ts();
        canLive = inAMinute(nowTs, startTs);
        TextView fullTv = findViewById(R.id.full_video_tv);
        fullTv.setText(canLive ? R.string.message_play_live : R.string.message_cloud_service_playback);
        requestShouldShowAi();

        if (StringUtils.equalsIgnoreCase(message.getTag(), EventConstants.TUMBLE_TAG)){
            messageTypeTv.setTextColor(getResources().getColor(R.color.global_customize_fixed_color_no_setting));
            setBackgroundColor(ResourcesUtil.getResources().getColor(R.color.global_customize_fixed_color_tumble));
        }

    }

    public void switchToVideoDownloadMode() {
        TGLog.i(TAG, "[switchToVideoDownloadMode] ");
        isVideoDownloadMode = true;
        if (isDownloadSuccess) {
            TGLog.i(TAG, "[switchToVideoDownloadMode] ignore because download before.");
            return;
        }
        downloadTypeTv.post(() -> downloadTypeTv.setText(R.string.label_download_video_local));
    }

    public void postAiFeedback(final boolean ok) {

        final MessageDataBean.ItemsBean eventMessage = messageDataHolder.getEventMessage();

        if (eventMessage == null || TextUtils.isEmpty(eventMessage.getRequestid())) return;

        HashMap<String, Object> params = new HashMap<>();
        params.put("device_id", eventMessage.getDevice_id());
        if (!TextUtils.isEmpty(eventMessage.getSub_tag())) {
            params.put("tag", eventMessage.getSub_tag());
        } else {
            params.put("tag", eventMessage.getTag());
        }
        params.put("image_path", eventMessage.getImage_path());
        params.put("request_id", eventMessage.getRequestid());
        params.put("ossid", eventMessage.getOssid());
        params.put("accurate", ok);

        TGHttp.getInstance().postAiFeedback(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ClientObserver<ShouldAiFeedbackBean>() {
                    @Override
                    protected void onSuccess(final ShouldAiFeedbackBean content) {
                        Log.i("asdasdasdsadsdds", "onSuccess: content = " + content);

                        aiFeedbackView.post(() -> {
                            aiFeedbackView.setVisibility(GONE);
                            if (ok) {
                                TGToast.showToast(R.string.label_feedback_been_submit);
                            } else {
                                TGToast.showToast(R.string.label_feedback_been_submit_2);
                            }
                        });
                    }

                    @Override
                    protected void onResponseError(int errorCode, String errorInfo) {
                        super.onResponseError(errorCode, errorInfo);
                        Log.i("asdasdasdsadsdds", "onResponseError: errorCode = " + errorCode);
                        Log.i("asdasdasdsadsdds", "onResponseError: errorInfo = " + errorInfo);
                    }

                    @Override
                    protected void onOtherError(String error) {
                        Log.i("asdasdasdsadsdds", "onOtherError: error = " + error);
                    }
                });
    }

    private void requestShouldShowAi() {
        final MessageDataBean.ItemsBean message = messageDataHolder.getEventMessage();

        if (message == null || TextUtils.isEmpty(message.getRequestid())) return;

        HashMap<String, String> params = new HashMap<>();
        params.put("device_id", message.getDevice_id());
        params.put("request_id", message.getRequestid());

        TGHttp.getInstance().shouldAiFeedback(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ClientObserver<EmptyBean>() {
                    @Override
                    protected void onSuccess(final EmptyBean content) {
                        aiFeedbackView.post(new Runnable() {
                            @Override
                            public void run() {
                                aiFeedbackView.setVisibility(View.VISIBLE);
                            }
                        });
                    }

                    @Override
                    protected void onResponseError(int errorCode, String errorInfo) {
                    }

                    @Override
                    protected void onOtherError(String error) {
                    }
                });
    }

    public static void setButtonEnable(@NonNull Button button, boolean enabled){
        button.setEnabled(enabled);
        button.setAlpha(enabled? 1.f : 0.4f);
    }


    private void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.layout_message_info, this);

        cloudServiceAdView = findViewById(R.id.cloud_service_ad_view);
        deviceTypeLayout = findViewById(R.id.line_device);
        addressView = findViewById(R.id.line_address);
        addressTv = findViewById(R.id.tv_address);

        aiFeedbackView = findViewById(R.id.ai_feedback_view);
        aiFeedbackViewYes = findViewById(R.id.ai_feedback_yes);
        aiFeedbackViewNo = findViewById(R.id.ai_feedback_no);

        aiFeedbackViewYes.setOnClickListener(v -> postAiFeedback(true));
        aiFeedbackViewNo.setOnClickListener(v -> postAiFeedback(false));

        backBtn = findViewById(R.id.back_btn);
        topContainer = findViewById(R.id.top_container);
        mapContainer = findViewById(R.id.map_container);

        statusBarHeight = (int) getResources().getDimension(R.dimen.status_bar_height);
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) topContainer.getLayoutParams();
        lp.topMargin = statusBarHeight;
        topContainer.setLayoutParams(lp);

        backBtn.setOnClickListener(v -> {
            if (getContext() instanceof Activity) {
                ((Activity) getContext()).finish();
            }
        });

        messageDetailTv = findViewById(R.id.tv_message_detail);

        messageTypeTv = findViewById(R.id.tv_event_type);
        messageAiIv = findViewById(R.id.icon_ai);

        dateTv = findViewById(R.id.tv_date);
        timeTv = findViewById(R.id.tv_time);

        deviceTypeIv = findViewById(R.id.icon_device);
        deviceNameTv = findViewById(R.id.tv_device_name);

        downloadView = findViewById(R.id.line_download);
        downloadTypeTv = findViewById(R.id.download_type_tv);
        fullVideoView = findViewById(R.id.line_full_video);
        downloadStatusIcon = findViewById(R.id.icon_download_status);
        downloadArrow = findViewById(R.id.icon_arrow_download);

        fullVideoView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickFull();
            }
        });

        downloadView.setOnClickListener(v -> {

            if (isDownloadSuccess) {
                // do nothing
            } else {
                download();
            }
        });

        alertSettingTv = findViewById(R.id.tv_alert_setting);
        alertSettingTv.setText(ClickableSpanHelper.getClickableSpanForMessage(alertSettingTv.getText().toString(), v -> {
            if (messageDataHolder.getDeviceItem() != null){
                IAppModule iAppModule = TGBusiness.getAppModule();
                if (messageDataHolder.getEventMessage() == null) return;
                if (TextUtils.equals(messageDataHolder.getEventMessage().getTag(), EventConstants.LOW_TEMP)
                        || TextUtils.equals(messageDataHolder.getEventMessage().getTag(), EventConstants.HIGH_TEMP)
                        || TextUtils.equals(messageDataHolder.getEventMessage().getTag(), EventConstants.LOW_HUMID)
                        || TextUtils.equals(messageDataHolder.getEventMessage().getTag(), EventConstants.HIGH_HUMID)) {

                }else {
                }

            } else {
                showToast(R.string.network_error);
            }
        }));
        alertSettingTv.setMovementMethod(LinkMovementMethod.getInstance());
    }




    private void download() {
        if (!XXPermissions.isGranted(getContext(), Permission.WRITE_EXTERNAL_STORAGE)) {
            String title = getContext().getString(com.module.appcommon.R.string.no_storage_permission_to_finish);
            String content = getContext().getString(com.module.appcommon.R.string.enable_permission_storage);
            PermissionUtil permissionUtil = new PermissionUtil(getContext());
            permissionUtil.checkPermissionFirst(Permission.WRITE_EXTERNAL_STORAGE, () -> {

            }, title, content);

            TGLog.i(TAG, "saveCoverToSdCard: no permission");
            return;
        }
        TGLog.i(TAG, "[download] isVideoDownloadMode = " + isVideoDownloadMode);

        if (isVideoDownloadMode) {
            if (messagePlayerView != null && messagePlayerView.saveVideo()) {
                updateDownloadStatus(true);
                Toast.makeText(getContext(), R.string.label_video_been_saved, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), R.string.video_is_downloading, Toast.LENGTH_SHORT).show();
            }
        } else {
            if (messagePlayerView != null && messagePlayerView.saveCover()) {
                updateDownloadStatus(true);
                Toast.makeText(getContext(), R.string.label_picture_been_saved, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), R.string.video_is_downloading, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public static boolean inAMinute(long endTimestamp, long startTimestamp) {
        return endTimestamp - startTimestamp <= 60;
    }

    private void onClickFull() {
        if (messageDataHolder.getEventMessage() == null) return;
        if (messageDataHolder.getEventMessage() != null && !TextUtils.isEmpty(messageDataHolder.getEventMessage().getUrl())) {
            if (TextUtils.equals(messageDataHolder.getEventMessage().getMessage_type(), EventConstants.NOTICE)) {
                IAppModule iAppModule = TGBusiness.getAppModule();
                iAppModule.openServePlay((Activity) getContext(), messageDataHolder.getEventMessage().getUrl(), Long.parseLong(messageDataHolder.getEventMessage().getDevice_id()), 0, Activity.RESULT_FIRST_USER);
            }
        } else {
            if (messageDataHolder.getDeviceItem() == null) {
                showToast(R.string.message_device_no_found);
                return;
            }

            IAppModule iAppModule = TGBusiness.getAppModule();
            iAppModule.onClickServeBtn((Activity) getContext(), canLive, messageDataHolder.getDeviceItem(), messageDataHolder.getEventMessage());
        }
    }

    public void onResume() {
        if (mIMapView != null) {
            mIMapView.resume();
        }
    }

    public void onSaveInstanceState(Bundle outState) {
        if (mIMapView != null){
            mIMapView.saveInstanceState(outState);
        }
    }

    public void onPause() {
        if (mIMapView != null) {
            mIMapView.pause();
        }
    }

    public void onDestroy() {
        if (mIMapView != null) {
            mIMapView.destroy();
        }
    }
}
